package utils

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	"log"
	"time"
	"NicePay/model"
)

var db *gorm.DB

func init() {
	log.Println("[SYS]", time.Now().Local().Format("01-02 15:04:05"), "▶ System [Database engining ...]")
	db = dbConn()
	db.AutoMigrate(
		model.Payment{},
		model.UserInfo{},
	)
}

func dbConn() *gorm.DB {
	cfg := GetConfig().Database
	dbStr := fmt.Sprintf("host=%s port=%d user=%s dbname=%s sslmode=disable password=%s",
		cfg.Address, cfg.Port, cfg.User, cfg.Name, cfg.Pass)
	db, err := gorm.Open("postgres", dbStr)
	if err != nil {
		log.Fatal(err)
	}
	db.DB().SetMaxIdleConns(cfg.MaxIdleConns)
	db.DB().SetMaxOpenConns(cfg.MaxOpenConns)
	return db
}

func Orm() *gorm.DB {
	if db == nil || db.DB().Ping() != nil {
		db = dbConn()
	}
	return db.New()
}
